using NaughtyAttributes;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rope : Climbable
{
    public Sprite headSprite;
    public Sprite bodySprite;
    public Sprite trailSprite;

    [Min(3)]
    public int length = 3;
    public float segmentWidth = 0.2f;
    public float segmentHeight = 1;

    private List<GameObject> segments;
    private BoxCollider2D col2D;
    private Vector2 size;
    private Vector2 offset;

    [Button("Generate")]
    public void Generate() 
    {
        if (segments == null)
        {
            segments = new List<GameObject>();
        }
        else 
        {
            for (int i = 0; i < segments.Count; i++) 
            {
                DestroyImmediate(segments[i]);
            }
            segments.Clear();
        }

        AddSegment(headSprite, "Head", 0);

        for (int i = 1; i < length - 1; i++) 
        {
            AddSegment(bodySprite, "Body_" + i, i);
        }

        AddSegment(trailSprite, "Trail", length - 1);

        col2D = GetComponent<BoxCollider2D>();
        if (col2D == null)
        {
            col2D = gameObject.AddComponent<BoxCollider2D>();  
        }

        size = new Vector2(segmentWidth, segmentHeight * (length - 0.5f));
        col2D.size = size;
        offset = new Vector2(0, size.y * -0.5f);
        col2D.offset = offset;
        col2D.isTrigger = true;
    }

    private void AddSegment(Sprite sprite, string name, int index) 
    {
        SpriteRenderer sp = new GameObject(name, typeof(SpriteRenderer)).GetComponent<SpriteRenderer>();
        sp.sprite = sprite;
        segments.Add(sp.gameObject);
        sp.transform.SetParent(transform);
        sp.transform.localPosition = new Vector3(0, index * -1f * segmentHeight, 0);
    }
}
